package com.zt.student.shiro;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.zt.common.common.ApiException;
import com.zt.common.common.CodeMsg;
import com.zt.student.pojo.WechatLoginCheck;
import com.zt.student.pojo.WechatToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * description:当且仅当传入为WechatToken时 即微信登录时进行校验 校验签名
 * author:zt
 * date:2021-12-02
 */

public class WechatRealm extends AuthorizingRealm {

    private static final Log log = LogFactory.get();

    /**
     * 限定只能处理自定义WechatToken
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof WechatToken;
    }



    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        WechatToken token = (WechatToken) auth;

        WechatLoginCheck wechat = (WechatLoginCheck) token.getCredentials();

        //rawData 与 signature是前端传进来，sessionKey为向微信服务器请求获得
        String rawData = wechat.getRawData();
        String signature = wechat.getSignature();
        String sessionKey = wechat.getSessionKey();

        // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
        String signature2 = DigestUtil.sha1Hex(rawData + sessionKey);
        if (!signature.equals(signature2)) {
            log.error("微信签名不匹配");
            throw new ApiException(CodeMsg.VERIFY_ERROR);
        }

        //这一步骤不做任何操作，即shiro不作校验
        return new SimpleAuthenticationInfo(token,token,getName());
    }
}
